<template>
  <div>
    <div class="title">
      <el-button type="text" style="padding-right: 10px;">标题</el-button>
      <el-input v-model="title" />
    </div>
    <div class="article">
      <Tinymce ref="editor" :height="400" @input="contentChenge" />
    </div>

    <div class="Preview">效果预览</div>
    <div class="content">
      <div v-html="content" />
    </div>
    <div class="btn">
      <el-button class="btn-save" type="primary" @click="saveClick">保存</el-button>
    </div>
  </div>
</template>

<script>
import { onBeforeMount, reactive, ref, toRefs } from "vue";
import Tinymce from "@/components/Tinymce";
import { createdArticle, getArticle, updateArticle } from "@/api/article";
import { useRoute } from "vue-router";
import { Message } from "element3";
export default {
  components: { Tinymce },
  setup() {
    const route = useRoute();
    const state = reactive({
      title: "",
      content: "",
    });
    function contentChenge(e) {
      state.content = e;
    }
    function saveClick() {
      const data = {
        title: state.title,
        content: state.content,
      };
      if (route.query.id) {
        updateArticle(route.query.id, data).then(() => {
          Message({
            message: "文章修改成功！",
            type: "success",
          });
        });
      } else {
        createdArticle(data).then(() => {
          Message({
            message: "文章创建成功",
            type: "success",
          });
        });
      }
    }
    // $refs
    const editor = ref(null);
    function articleDetail(id) {
      getArticle(id).then((res) => {
        setTimeout(() => {
          state.title = res.data.title;
          state.content = res.data.content;
          editor.value.setContent(state.content);
        }, 150);
      });
    }
    onBeforeMount(() => {
      if (route.query.id) {
        articleDetail(route.query.id);
      }
    });
    return {
      ...toRefs(state),
      saveClick,
      contentChenge,
      editor,
    };
  },
};
</script>

<style lang="scss">
.title{
  display: flex;
  padding: 10px 20px;
}
.article {
  margin: 20px 20px;
}
.content {
  width: 820px;
  margin: 0 auto;
  border: 1px solid #ccc;
  margin-bottom: 30px;
  padding: 10px;
  text-align: initial;
  p {
    word-wrap: break-word;
  }
}
.Preview{
  font-size: 18px;
  padding-left: 20px;
}
.btn{
  width: 820px;
  margin: auto;
  &-save{
    float: right;
    margin: 20px 0;
  }
}

</style>
